/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.common.base.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.je.common.base.DynaBean;
import com.je.common.base.entity.extjs.Model;
import com.je.common.auth.impl.account.Account;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.PcDbSQLService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.DBSqlUtils;
import com.je.common.base.util.JdbcUtil;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class PcDbSQLServiceImpl implements PcDbSQLService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private BeanService beanService;

    /**
     * 查询数据
     * @param sql sql语句
     * @return
     */
    @Override
    public List<Model> selectModel(String sql){
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        List<Model> models=new ArrayList<Model>();
        try{
            connection = metaService.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            ResultSetMetaData data = resultSet.getMetaData();
            int count = data.getColumnCount();
            for (int i = 1; i <= count; i++) {
                // 获得指定列的列名
                String columnName = data.getColumnName(i);
                Integer type=data.getColumnType(i);
                Model model = DBSqlUtils.getExtModel(columnName, type);
                if(model!=null){
                    models.add(model);
                }
            }
        }catch(Exception e){
//			e.printStackTrace();
            throw new PlatformException("根据SQL获取列信息失败!", PlatformExceptionEnum.JE_CORE_SQL_MODEL_ERROR,new Object[]{sql},e);
        }finally{
            JdbcUtil.close(resultSet, statement, connection);
        }
        return models;
    }

    /**
     * 查询出SQL的名称
     * @param sql sql语句
     * @return
     */
    @Override
    public List<DynaBean> select(String sql){
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        List<DynaBean> beans=new ArrayList<DynaBean>();
        try{
            connection= metaService.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            ResultSetMetaData data = resultSet.getMetaData();
            int count = data.getColumnCount();
            while (resultSet.next()) {
                DynaBean bean=new DynaBean();
                for (int i = 1; i <= count; i++) {
                    // 获得指定列的列名
                    String columnName = data.getColumnName(i);
                    Object obj=resultSet.getObject(i);
                    if(obj instanceof Clob){
                        bean.set(columnName, StringUtil .getClobValue(obj));
                    }else {
                        String columnValue = StringUtil.getDefaultValue(obj, "");
                        if(StringUtil.isNotEmpty(columnName)){
                            bean.set(columnName, columnValue);
                        }
                    }
                }
                beans.add(bean);
            }
        }catch (Exception e) {
//			e.printStackTrace();
            throw new PlatformException("根据SQL获取数据信息失败!", PlatformExceptionEnum.JE_CORE_SQL_DATA_ERROR,new Object[]{sql},e);
        }finally{
            JdbcUtil.close(resultSet, statement, connection);
        }
        return beans;
    }

    /**
     * 查询出SQL的名称
     * @param sql sql语句
     * @param limit 分页
     * @return
     */
    @Override
    public List<DynaBean> select(String sql, int limit) {
        List<DynaBean> beans=new ArrayList<DynaBean>();
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try{
            connection = metaService.getConnection();
            statement = connection.createStatement();
            if(limit>0){
                statement.setMaxRows(limit);
            }
            resultSet = statement.executeQuery(sql);
            ResultSetMetaData data = resultSet.getMetaData();
            int count = data.getColumnCount();
            while (resultSet.next()) {
                DynaBean bean=new DynaBean();
                for (int i = 1; i <= count; i++) {
                    // 获得指定列的列名
                    String columnName = data.getColumnName(i);
                    Object obj=resultSet.getObject(i);
                    if(obj instanceof Clob){
                        bean.set(columnName, StringUtil.getClobValue(obj));
                    }else {
                        String columnValue = StringUtil.getDefaultValue(obj, "");
                        if(StringUtil.isNotEmpty(columnName)){
                            bean.set(columnName, columnValue);
                        }
                    }
                }
                beans.add(bean);
            }
        }catch(Exception e){
            throw new PlatformException("根据SQL获取指定列数数据信息失败!", PlatformExceptionEnum.JE_CORE_SQL_DATA_ERROR,new Object[]{sql,limit},e);
        }finally{
            JdbcUtil.close(resultSet, statement, connection);
        }
        return beans;
    }

    /**
     * 执行前台的事务操作
     * @param arrays
     * @param currentAccount 当前登陆人信息
     */
    @Override
    public void doTransaction(JSONArray arrays, Account currentAccount) {
        for(Integer i=0;i<arrays.size();i++){
            JSONObject task=arrays.getJSONObject(i);
            String taskKey=task.getString("taskKey");
            if("insert".equals(taskKey)){
                JSONObject config=task.getJSONObject("config");
                String tableCode=config.getString("tableCode");
                DynaBean dynaBean=new DynaBean(tableCode,true);
                dynaBean.setJsonValues(config.getJSONObject("values"));
                commonService.buildModelCreateInfo(dynaBean,currentAccount);
                metaService.insert(dynaBean);
            }else if("remove".equals(taskKey)){
                JSONObject config=task.getJSONObject("config");
                String tableCode=config.getString("tableCode");
                String whereSql=config.getString("whereSql");
                metaService.delete(tableCode, ConditionsWrapper.builder().apply(whereSql));
            }else if("removeByIds".equals(taskKey)){
                JSONObject config=task.getJSONObject("config");
                String tableCode=config.getString("tableCode");
                String ids=config.getString("ids");
                String pkCode = beanService.getPKeyFieldNamesByTableCode(tableCode);
                metaService.delete(tableCode,ConditionsWrapper.builder().in(pkCode, Splitter.on(",").splitToList(ids)));
            }else if("update".equals(taskKey)){
                JSONObject config=task.getJSONObject("config");
                String tableCode=config.getString("tableCode");
                DynaBean dynaBean=new DynaBean(tableCode,true);
                dynaBean.setJsonValues(config.getJSONObject("values"));
                commonService.buildModelModifyInfo(dynaBean,currentAccount);
                metaService.update(dynaBean);
            }else if("updateBatch".equals(taskKey)){
                JSONObject config=task.getJSONObject("config");
                String tableCode=config.getString("tableCode");
                DynaBean dynaBean=new DynaBean(tableCode,true);
                dynaBean.setJsonValues(config.getJSONObject("values"));
                dynaBean.set(BeanService.KEY_WHERE, config.getString("whereSql"));
//                commonService.listUpdate(dynaBean);
            }else if("sql".equals(taskKey)){
                String sql=task.getString("config");
                metaService.executeSql(sql);
            }
        }
    }

}
